/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudexapps.manager.resolvers;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.webflow.conversation.NoSuchConversationException;
import org.springframework.webflow.execution.repository.snapshot.SnapshotNotFoundException;

public class FlowHandlerExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request,
	    HttpServletResponse response, Object handler, Exception exception) {

	Throwable rootException = ExceptionUtils.getRootCause(exception);
	if (rootException instanceof NoSuchConversationException) {
	    // TODO Remove the flow here
	    ModelAndView mav = new ModelAndView("intro");
	    return mav;
	} else if (rootException instanceof IOException) {
	    return handleIOException((IOException) rootException, request);
	} else if (rootException instanceof SnapshotNotFoundException) {
	    ModelAndView mav = new ModelAndView("intro");
	    return mav;
	} else {
	    ModelAndView mav = new ModelAndView("error/defaultError");
	    return mav;
	}
    }

    @ExceptionHandler(IOException.class)
    public ModelAndView handleIOException(IOException ex,
	    HttpServletRequest request) {
	ModelAndView mav = new ModelAndView("error/defaultError");
	return mav;
    }
}
